// pages/device/use/index.js
var app = getApp(), fetchApi = require("../../../utils/httpPost.js"), 
common_Js = require("../../../component/common.js"),
formatTime = require("../../../utils/formatTime.js");
import Dialog from '../../../component/vant/dialog/dialog';
import Toast from '../../../component/vant/toast/toast';
Page({

    /**
     * 页面的初始数据
     */
    data: {
        isLoading: true, 
        loading: false, 
        netWork: false,
        submitState:false,
        device_id:0,
        device:{},
        wd:0,
        jd:0,
        isShowPop:false,
        isShowPopMin:false,
        isShowPopMax:false,
        nowDate:'',
        beginTime:'00:00',
        endTime:'23:59',
        currentDate: new Date().getTime(),
        minDate: new Date(2023, 0, 1).getTime(),
        currentTime: new Date(),
        currentTimeMin:'00:00',
        currentTimeMax:'23:59',
        beginTimeTemp: null,
        useHour: '1小时', //作业时长
        hourColumns: ['1小时', '2小时', '3小时', '4小时', '5小时', '6小时', '7小时', '8小时'],
        use_address:'',
        fileList1: [],
        fileList2: [],
        useState: 1,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        var that = this;
        console.log('use  options',options)
        if(options.q){
            var q = decodeURIComponent(options.q) // 获取到二维码原始链接内容
            const scancode_time = parseInt(options.scancode_time) // 获取用户扫码时间 UNIX 时间戳
            q = "?" + q.split("?")[1];
            this.data.query = q;
            console.log('q',q)
            options = this.getQueryVariable(q);
            console.log('options',options)
            var device_id = parseInt(options.id) ;
            that.data.device_id = device_id;
          }else{

            if(options.id){
                this.data.device_id = parseInt(options.id);
            }
        }

        if(options.useState){
          this.data.useState = parseInt(options.useState);
        }
        var ss = common_Js.formatTimeSimple(new Date());
          var date = new Date();
          //年 getFullYear()：四位数字返回年份
          var year = date.getFullYear(); //getFullYear()代替getYear()
          //月 getMonth()：0 ~ 11
          var month = date.getMonth() + 1;
          //日 getDate()：(1 ~ 31)
          var day = date.getDate();
          //时 getHours()：(0 ~ 23)
          var hour = date.getHours();
          //分 getMinutes()： (0 ~ 59)
          var minute = date.getMinutes();
          //秒 getSeconds()：(0 ~ 59)
          var second = date.getSeconds();

          var minHour = 0;
          if(hour == 0){
            minHour = 0;
          }else{
            minHour = hour;
          }
          var maxHour = hour + 1;
      
          var hourBeginStr = minHour < 10 ? '0' + minHour : minHour;
    
          var minuteStr= minute < 10 ? '0' + minute : minute;
          hourBeginStr += ':' + minuteStr;
    
          var hourEndStr = maxHour < 10 ? '0' + maxHour : maxHour;
          hourEndStr += ':' + minuteStr;
      
          this.data.beginTime = hourBeginStr;
      
          this.data.nowDate = ss;
      
          this.data.currentTime = formatTime.dateStrChangeTime(this.data.nowDate + ' ' + this.data.beginTime + ':00');
      
          this.data.endTime = ss + ' ' + hourEndStr;
      
          this.data.beginTimeTemp = ss + ' ' + this.data.beginTime + ':00';
      
          console.log('currentTime', this.data.currentTime);
          console.log('beginTime', this.data.beginTime);
          console.log('endTime', this.data.endTime);
      
          this.setData({
            nowDate: ss,
            beginTime: hourBeginStr,
          })

        this.onHttpInit();
    },
  /**
   * 获取页面数据的 http请求
   */
  onHttpInit: function () {
    console.log('onHttpInit')
    var that = this;
    fetchApi.httpPost('/device/welding/detail', {
      device_id:that.data.device_id,
    }, function (res) {
      console.log("传感器设备上报记录响应数据", res)
      if (res.data.code == 0) {
        that.setData({
          device: res.data.data.device,
        })
      }
      that.setData({
         isLoading: false, loading: true, netWork: true,
      })
    }, function (res) {
        that.setData({ hasData: false,  isLoading: false,  loading: true, netWork: true })
    })
  },
  /**
   * 获取页面数据的 http请求
   */
  onHttpSubmit: function (e) {
    if(this.data.device.useState == 0){
      // if(this.data.device.isSafe == 0 && this.data.use_address == ''){
      //   Toast('请填写作业地点')
      //   return;
      // }
  
      // if(this.data.fileList1.length == 0){
      //   Toast('请上传作业地点图片')
      //   return;
      // }
  
      // if(this.data.fileList2.length == 0){
      //   Toast('请上传安全措施图片')
      //   return;
      // }
    }

    this.data.submitState = true;
    this.setData({
      submitState:true
    })

    var use_state = e.currentTarget.dataset.usestate;
    var that = this;
    fetchApi.httpPost('/device/welding/add/record/safe', {
      device_id:that.data.device_id,
      use_state: use_state,
      begin_time: that.data.nowDate +' '+ that.data.beginTime,
      end_time:  that.data.endTime,
      use_address: that.data.use_address,
    }, function (res) {
      console.log("发起申请响应数据", res)
      if (res.data.code == 0) {
          Toast.success(res.data.msg);
          var record_id = res.data.data;
          
          console.log('that.data.fileList1',that.data.fileList1)
          if (record_id > 0 && that.data.fileList1.length > 0) {
            for (var index in that.data.fileList1) {
              wx.uploadFile({
                url: fetchApi.getPlatformUrl() + '/device/welding/uploadImg',
                filePath: that.data.fileList1[index].url,
                name: 'file',
                formData: { record_id: record_id,img_type: 0 },
                success: function (res) {
                  console.log('uploadFile success res', res)
                }, fail: function (res) {
                  console.log('uploadFile fail res', res)
                }
              })
            }
          }
          
          console.log('that.data.fileList2',that.data.fileList2)
          if (record_id > 0 && that.data.fileList2.length > 0) {
            for (var index in that.data.fileList2) {
              wx.uploadFile({
                url: fetchApi.getPlatformUrl() + '/device/welding/uploadImg',
                filePath: that.data.fileList2[index].url,
                name: 'file',
                formData: { record_id: record_id,img_type: 1 },
                success: function (res) {
                  console.log('uploadFile success res', res)
                }, fail: function (res) {
                  console.log('uploadFile fail res', res)
                }
              })
            }
          }

          
            that.data.submitState = false;
            that.setData({
                submitState:false
            })
          
          setTimeout(function(){
            // wx.navigateBack({
            //     delta:-1
            // })
            wx.redirectTo({
              url: '/pages/welding/record/index',
            })
          },800)
      }else{
        Toast.fail(res.data.msg);
      }
      that.setData({
         isLoading: false, loading: true, netWork: true,
      })
    }, function (res) {
        that.setData({ hasData: false,  isLoading: false,  loading: true, netWork: true })
    })
  },

  deleteImg1:function(res){
    console.log('删除图片',res)
    var index = res.currentTarget.dataset.index;
    this.data.fileList1 = [];
    this.setData({ fileList1 :this.data.fileList1 });
  },
  deleteImg2:function(res){
    console.log('删除图片',res)
    var index = res.currentTarget.dataset.index;
    this.data.fileList2 = [];
    this.setData({ fileList2 :this.data.fileList2 });
  },
  afterRead(event) {
    console.log('afterRead',event)
    const { file, name } = event.detail;
    console.log('afterRead name',name)
    console.log('afterRead file',file)
    const fileList = this.data[`fileList${name}`];
    
    this.setData({ [`fileList${name}`]: fileList.concat(file) });
    
    console.log('afterRead fileList',fileList)
    if(name == "1"){
      this.data.fileList1.concat(file)
      console.log('fileList',this.data.fileList1)
    }else{
      this.data.fileList2.concat(file)
      console.log('fileList',this.data.fileList2)
    }
  },
  oversize() {
    wx.showToast({ title: '文件超出大小限制', icon: 'none' });
  },
  onConfirmHour(e){
    console.log('onConfirmHour',e);    
    var type = e.currentTarget.dataset.htype;
    var time = e.detail;
    if(type == 'min'){
      this.data.beginTime = time;
      this.setData({
        beginTime:time
      })
      this.onClickDateMin();
    }else{
      this.data.endTime = time;
      this.setData({
        endTime:time
      })
      this.onClickDateMax()
    }
   },
  onClickDate(){
    this.setData({
      isShowPop : !this.data.isShowPop
    })
  },
  onClickDateMin(){
    this.setData({
      isShowPopMin : !this.data.isShowPopMin
    })
  },
  onClickDateMax(){
    this.setData({
     isShowPopMax : !this.data.isShowPopMax
    })
  },
  
  onConfirmUseHour(e) {
    console.log('onConfirmHour', e);
    var index = e.detail.index;

    var beginTime = formatTime.dateStrChangeTime(this.data.beginTimeTemp);
    console.log('beginTime', beginTime);
    this.data.currentTime = beginTime;

    var endTime = beginTime.setHours(beginTime.getHours() + (index + 1));
    var time = formatTime.formatTimeMinute(endTime);
    console.log('endTime', time);
    this.data.endTime = time;

    var hour = e.detail.value;

    this.setData({
      useHour: hour,
    })
    this.onClickDateMax()
  },
  onCancle(){
    this.setData({
      isShowPop: false
    })
  },
  onCancleHour() {
    this.setData({
      isShowPopMin: false,
      isShowPopMax: false
    })
  },
  bindInput(e){
    var key = e.currentTarget.dataset.key;
    if(key == 'address'){
      this.data.use_address = e.detail || "";
    }
  },
  getResult(time, type) {
    const date = new Date(time);
    switch (type) {
      case 'datetime':
        return date.toLocaleString();
      case 'date':
        return date.toLocaleDateString();
      case 'year-month':
        return `${date.getFullYear()}/${date.getMonth() + 1}`;
      case 'time':
        return time;
      default:
        return '';
    }
  },
  formatData(type, value) {
    if (type === 'year') {
      return `${value}年`;
    }
    if (type === 'month') {
      return `${value}月`;
    }
    return value;
  },
  touchHandler: function (e) { //当月用电触摸显示
   yuelineChart.showToolTip(e, { //showToolTip图表中展示数据详细内容
    background: '#7cb5ec',
    format: function (item, category) {
     return category + '日 ' + item.name + ':' + item.data
    }
   });
  },
  getQueryVariable(url){
    //返回当前 URL 的查询部分（问号 ? 之后的部分）。
    var urlParameters = url;// location.search;
    //声明并初始化接收请求参数的对象
    var requestParameters = new Object();
    var parameterArray = [];
    //如果该求青中有请求的参数，则获取请求的参数，否则打印提示此请求没有请求的参数
    if (urlParameters.indexOf('?') != -1)
    {
        //获取请求参数的字符串
        var parameters = decodeURI(urlParameters.substr(1));
        //将请求的参数以&分割中字符串数组
        parameterArray = parameters.split('&');
        //循环遍历，将请求的参数封装到请求参数的对象之中
        for (var i = 0; i < parameterArray.length; i++) {
            requestParameters[parameterArray[i].split('=')[0]] = (parameterArray[i].split('=')[1]);
        }
        console.info('theRequest is =====',requestParameters);
    } else
    {
        console.info('There is no request parameters');
    }
    return requestParameters;
  },
})